<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">系统登录</h2>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        @keyup.enter.native="handleLogin"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            clearable
          >
            <template #suffix>
              <i
                :class="passwordVisible ? 'el-icon-view' : 'el-icon-minus'"
                @click="passwordVisible = !passwordVisible"
                style="cursor: pointer;"
              />
            </template>
          </el-input>
        </el-form-item>

        <!-- 记住密码 -->
        <el-checkbox v-model="rememberPassword">记住密码</el-checkbox>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            style="width: 100%;"
          >
            {{ loading ? '登录中...' : '立即登录' }}
          </el-button>
        </el-form-item>

        <!-- 忘记密码 -->
        <div class="forgot-password">
          <el-link type="info" @click="showForgotPassword">忘记密码？</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, message: '密码长度至少4位', trigger: 'blur' }
        ]
      },
      passwordVisible: false,
      rememberPassword: false,
      loading: false
    };
  },
  mounted() {
    // 自动填充记住的密码
    const savedUsername = localStorage.getItem('username');
    const savedPassword = localStorage.getItem('password');
    if (savedUsername && savedPassword) {
      this.loginForm.username = savedUsername;
      this.loginForm.password = savedPassword;
      this.rememberPassword = true;
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 调用登录接口
          axios.post('/user/login', new URLSearchParams({
            username: this.loginForm.username,
            password: this.loginForm.password
          }), {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          })
            .then(response => {
              if (response.data.state === 'success') {
                // 存储用户ID和角色
                const user = response.data.user;
                localStorage.setItem('userid', user.userid.toString()); // 确保转换为字符串
                localStorage.setItem('role', user.role);
                // 无论是否勾选“记住密码”，始终存储用户名
                localStorage.setItem('username', user.username);
                localStorage.setItem('realname', user.realname);
                // 记住密码
                if (this.rememberPassword) {
                  localStorage.setItem('username', this.loginForm.username);
                  localStorage.setItem('password', this.loginForm.password);
                } else {
                  localStorage.removeItem('username');
                  localStorage.removeItem('password');
                }
                // 跳转到主页
                this.$router.push('/home/notice');
              } else {
                Message.error(response.data.message || '登录失败');
              }
            })
            .catch(error => {
              Message.error(
                (error.response && error.response.data && error.response.data.message)
                || '网络错误'
              );
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    showForgotPassword() {
      this.$alert('请联系管理员重置密码', '忘记密码', {
        confirmButtonText: '确定'
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #6b73ff 0%, #000dff 100%);
}

.login-card {
  width: 400px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.forgot-password {
  text-align: center;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .login-card {
    width: 90%;
    margin: 0 auto;
  }
}
</style>
